package cn.pedant.SafeWebViewBridge.sample;

import cn.pedant.SafeWebViewBridge.InjectedChromeClient;
import cn.pedant.SafeWebViewBridge.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.webengine.JsMessageResult;
import ohos.agp.components.webengine.JsTextInputResult;
import ohos.agp.components.webengine.WebConfig;
import ohos.agp.components.webengine.WebView;
import ohos.app.Context;

public class WebAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initView();
    }

    private void initView() {
        DirectionalLayout layout = (DirectionalLayout) findComponentById(ResourceTable.Id_web_layout);
        WebView wv = new WebView(this);
        wv.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);
        wv.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);
        layout.addComponent(wv);
        WebConfig ws = wv.getWebConfig();
        ws.setDataAbilityPermit(true);
        ws.setJavaScriptPermit(true);
        wv.setBrowserAgent(
                new CustomChromeClient(this, "HostApp", HostJsScope.class)
        );
        wv.load("dataability://cn.pedant.SafeWebViewBridge.ExampleDataAbility/rawfile/test.html");
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    static class CustomChromeClient extends InjectedChromeClient {
        /**
         * 构造
         *
         * @param context 上下文
         * @param injectedName 类名
         * @param injectedCls 类
         */
        public CustomChromeClient(Context context, String injectedName, Class injectedCls) {
            super(context, injectedName, injectedCls);
        }

        @Override
        public boolean onJsMessageShow(
                WebView webView, String url, String message, boolean isAlert, JsMessageResult result) {
            return super.onJsMessageShow(webView, url, message, isAlert, result);
        }

        @Override
        public boolean onJsTextInput(
                WebView webView, String url, String message, String defaultInput, JsTextInputResult result) {
            return super.onJsTextInput(webView, url, message, defaultInput, result);
        }

        @Override
        public void onProgressUpdated(WebView webView, int newValue) {
            super.onProgressUpdated(webView, newValue);
        }
    }
}
